package com.uroad.lib.widget.qozix.tileview.samples;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.View;

import com.uroad.lib.widget.qozix.tileview.detail.DetailLevel;
import com.uroad.lib.widget.qozix.tileview.detail.DetailLevelEventListener;
import com.uroad.lib.widget.qozix.tileview.detail.DetailManager;


public class SampleManager extends View implements DetailLevelEventListener {

	private DetailManager detailManager;
	// private BitmapDecoder decoder = new BitmapDecoderAssets();
	// private BitmapDecoder decoder = BitmapDecoderMemory.getInstance();

	private Rect area = new Rect(0, 0, 0, 0);

	private Bitmap bitmap;
	private String lastFileName;

	public SampleManager(Context context, DetailManager dm) {

		super(context);

		detailManager = dm;
		detailManager.addDetailLevelEventListener(this);

		update();

	}

	// public void setDecoder( BitmapDecoder d ){
	// decoder = d;
	// }

	public void clear() {
		bitmap = null;
		lastFileName = null;
	}

	public void update() {
		DetailLevel detailLevel = detailManager.getCurrentDetailLevel();
		if (detailLevel != null) {
			String fileName = detailLevel.getDownsample();
			if (fileName != null) {
				if (!fileName.equals(lastFileName)) {
					bitmap = getBitmap();
					invalidate();
				}
			}
			lastFileName = fileName;
		}
	}

	public Bitmap getBitmap() {
		return bitmap;
	}

	public void setBitmap(Bitmap bitmap) {
		if (bitmap == this.bitmap) {

		} else {
			if (this.bitmap != null){
				this.bitmap.recycle();
				System.gc();
			}
				
			this.bitmap = bitmap;
		}
		// this.bitmap = bitmap;
	}

	public void updateBitmap() {
		// bitmap = decoder.decode( "", null );
		invalidate();
	}

	@Override
	public void onDetailLevelChanged() {
		update();
	}

	@Override
	public void onDetailScaleChanged(double s) {

	}

	@Override
	public void onDraw(Canvas canvas) {
		if (bitmap != null) {
			area.right = getWidth();
			area.bottom = getHeight();
			canvas.drawBitmap(bitmap, null, area, null);
		}
		super.onDraw(canvas);
	}
}
